/**
 * filter.js
 * @author Ulyan Sobin
 * @description Filter module
 */

const { ErrorView } = require(".");
const { WebNode, WebClient, WebRequest } = require("./cube-web");

class WebFilter extends WebNode {

	/** @type {function (WebRequest): boolean} */
	filter;

	/** @type {WebNode} */
	resolve;

	/** @type {?WebNode} */
	reject;

	/** 
	 * @param {function (WebRequest): boolean} filter
	 * If returns `true`, it will pass the filter. Otherwise, the request will be reject.
	 * @param {WebNode} resolve
	 * It will be access when the filter be passed.
	 * @param {?WebNode} reject
	 * It will be access when the request be rejected.
	 */
	constructor (filter, resolve, reject) {
		super();
		this.filter = filter;
		this.resolve = resolve;
		if (reject instanceof WebNode) this.reject = reject;
		else this.reject = new ErrorView(400, "BAD REQUEST");
	}

	/**
	 * @override
	 * @param {WebClient} client 
	 */
	route(client) {
		new Promise((resolve, _) => {
			resolve(this.filter(client.request));
		}).then((passed) => {
			if (passed) this.resolve.route(client);
			else this.reject.route(client);
		}).catch((err) => {
			this.reject.route(client);
		});
	}
}

module.exports.WebFilter = WebFilter;